package com.example.util;

import com.example.config.JedisClusterProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisCluster;

import javax.annotation.PostConstruct;

@Service
public class RedisService {

    @Autowired
    private JedisCluster jedisCluster;

    private String prefix;
    private Integer expire;

    @Autowired
    private JedisClusterProperties jedisClusterProperties;

    @PostConstruct
    private void init(){
        JedisClusterProperties.Cache jedisClusterPropertiesCache = jedisClusterProperties.getCache();
        this.prefix = jedisClusterPropertiesCache.getPrefix();
        this.expire = jedisClusterPropertiesCache.getExpire();
        String split = jedisClusterPropertiesCache.getSplit();

        if (prefix == null) {
            prefix = "";
        } else if (!StringUtils.isEmpty(prefix)) {
            prefix += split;
        }
    }

    public String get(final String key){
        return jedisCluster.get(prefix + key);
    }

    public String set(final String key, final String value){
        return jedisCluster.setex(prefix + key, expire, value);
    }

    public String setex(final String key, final int expire, final String value) {
        return jedisCluster.setex(prefix+key, expire, value);
    }


}
